import { defineComponent, reactive, ref, toRefs } from 'vue'
import {
  NForm,
  NFormItem,
  NModal,
  NSelect,
  SelectOption,
  FormRules
} from 'naive-ui'
import { Response } from '@/service/modules/common/types'
import { updateProAdminsReq } from '@/service/modules/project'
import { searchUserByUsernameReq } from '@/service/modules/user'

const SetProjectManagerModal = defineComponent({
  name: 'SetProjectManagerModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    proId: {
      type: Number,
      required: true
    }
  },
  emits: ['modalShowChange'],
  setup() {
    const state = reactive({
      userIds: [],
      positiveButtonDisabled: false,
      rules: {
        userIds: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.userIds.length === 0) {
              return new Error(window.$t('project.projectManagerTips'))
            }
          }
        }
      } as FormRules
    })
    const loadingRef = ref(false)
    const optionsRef = ref<SelectOption[]>([])
    return { ...toRefs(state), loadingRef, optionsRef }
  },
  methods: {
    async onPositiveClick() {
      //提交修改项目管理员请求
      this.positiveButtonDisabled = true
      const res: Response<any> = await updateProAdminsReq(
        this.proId,
        this.userIds
      ).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.userIds = []
    },
    async handleSearch(query: string) {
      if (!query.length) {
        this.optionsRef = []
        return
      }
      this.loadingRef = true
      const res = await searchUserByUsernameReq({ username: query }).catch(
        () => {
          this.loadingRef = false
        }
      )
      if (res.resp_code === 0) {
        this.optionsRef = res.data
      }
      this.loadingRef = false
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('project.setProjectManagers')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        positiveButtonProps={{
          disabled: this.positiveButtonDisabled || this.userIds.length === 0
        }}
        onClose={this.onNegativeClick}
      >
        <NForm
          rules={this.rules}
          label-placement='left'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem
            path='userIds'
            label={window.$t('project.projectManagers')}
          >
            <NSelect
              v-model:value={this.userIds}
              filterable
              multiple
              placeholder={window.$t('user.searchUser')}
              options={this.optionsRef}
              label-field='username'
              value-field='id'
              loading={this.loadingRef}
              clearable
              remote
              clear-filter-after-select
              onSearch={this.handleSearch}
            ></NSelect>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default SetProjectManagerModal
